/**
 * 业务错误处理工具类
 * 用于区分业务逻辑错误和系统错误，提供更友好的错误提示
 * @author Wu.Liang
 * @date 2025-01-30
 */

import { ElMessage, ElNotification } from 'element-plus'

/**
 * 业务错误类型枚举
 */
export enum BusinessErrorType {
  PERMISSION_DENIED = 'PERMISSION_DENIED',           // 权限不足
  DATA_NOT_FOUND = 'DATA_NOT_FOUND',                 // 数据不存在
  BUSINESS_RULE_VIOLATION = 'BUSINESS_RULE_VIOLATION', // 业务规则违反
  VALIDATION_ERROR = 'VALIDATION_ERROR',             // 数据验证错误
  OPERATION_FAILED = 'OPERATION_FAILED',             // 操作失败
  UNKNOWN_BUSINESS_ERROR = 'UNKNOWN_BUSINESS_ERROR'  // 未知业务错误
}

/**
 * 业务错误接口
 */
export interface BusinessError {
  type: BusinessErrorType
  message: string
  code?: number
  details?: any
}

/**
 * 业务错误处理器类
 */
export class BusinessErrorHandler {
  /**
   * 处理业务错误
   * @param error 错误信息
   * @param options 处理选项
   */
  static handle(error: string | BusinessError, options: {
    showMessage?: boolean
    showNotification?: boolean
    logToConsole?: boolean
    silent?: boolean
  } = {}): void {
    const {
      showMessage = true,
      showNotification = false,
      logToConsole = false,
      silent = false
    } = options

    // 解析错误信息
    const businessError = this.parseError(error)
    
    // 静默模式，不显示任何提示
    if (silent) {
      return
    }

    // 显示消息提示
    if (showMessage) {
      this.showMessage(businessError)
    }

    // 显示通知
    if (showNotification) {
      this.showNotification(businessError)
    }

    // 控制台日志（仅在开发环境或明确要求时）
    if (logToConsole && process.env.NODE_ENV === 'development') {
      console.warn('业务错误:', businessError)
    }
  }

  /**
   * 解析错误信息
   */
  private static parseError(error: string | BusinessError): BusinessError {
    if (typeof error === 'string') {
      return {
        type: this.detectErrorType(error),
        message: error
      }
    }
    return error
  }

  /**
   * 检测错误类型
   */
  private static detectErrorType(message: string): BusinessErrorType {
    const lowerMessage = message.toLowerCase()
    
    if (lowerMessage.includes('权限') || lowerMessage.includes('permission') || lowerMessage.includes('无权限')) {
      return BusinessErrorType.PERMISSION_DENIED
    }
    if (lowerMessage.includes('不存在') || lowerMessage.includes('not found') || lowerMessage.includes('未找到')) {
      return BusinessErrorType.DATA_NOT_FOUND
    }
    if (lowerMessage.includes('验证') || lowerMessage.includes('validation') || lowerMessage.includes('格式')) {
      return BusinessErrorType.VALIDATION_ERROR
    }
    if (lowerMessage.includes('规则') || lowerMessage.includes('rule') || lowerMessage.includes('违反')) {
      return BusinessErrorType.BUSINESS_RULE_VIOLATION
    }
    if (lowerMessage.includes('失败') || lowerMessage.includes('failed') || lowerMessage.includes('错误')) {
      return BusinessErrorType.OPERATION_FAILED
    }
    
    return BusinessErrorType.UNKNOWN_BUSINESS_ERROR
  }

  /**
   * 显示消息提示
   */
  private static showMessage(error: BusinessError): void {
    const { type, message } = error
    
    switch (type) {
      case BusinessErrorType.PERMISSION_DENIED:
        ElMessage.warning({
          message: `权限不足：${message}`,
          duration: 4000,
          showClose: true
        })
        break
      case BusinessErrorType.DATA_NOT_FOUND:
        ElMessage.info({
          message: `数据不存在：${message}`,
          duration: 3000,
          showClose: true
        })
        break
      case BusinessErrorType.VALIDATION_ERROR:
        ElMessage.error({
          message: `数据验证失败：${message}`,
          duration: 4000,
          showClose: true
        })
        break
      case BusinessErrorType.BUSINESS_RULE_VIOLATION:
        ElMessage.warning({
          message: `业务规则限制：${message}`,
          duration: 4000,
          showClose: true
        })
        break
      case BusinessErrorType.OPERATION_FAILED:
        ElMessage.error({
          message: `操作失败：${message}`,
          duration: 4000,
          showClose: true
        })
        break
      default:
        ElMessage.warning({
          message: message,
          duration: 3000,
          showClose: true
        })
        break
    }
  }

  /**
   * 显示通知
   */
  private static showNotification(error: BusinessError): void {
    const { type, message } = error
    
    let notificationType: 'success' | 'warning' | 'error' | 'info' = 'info'
    
    switch (type) {
      case BusinessErrorType.PERMISSION_DENIED:
        notificationType = 'warning'
        break
      case BusinessErrorType.DATA_NOT_FOUND:
        notificationType = 'info'
        break
      case BusinessErrorType.VALIDATION_ERROR:
      case BusinessErrorType.OPERATION_FAILED:
        notificationType = 'error'
        break
      case BusinessErrorType.BUSINESS_RULE_VIOLATION:
        notificationType = 'warning'
        break
      default:
        notificationType = 'info'
        break
    }

    ElNotification({
      title: '业务提示',
      message: message,
      type: notificationType,
      duration: 4000,
      showClose: true
    })
  }

  /**
   * 处理权限错误
   */
  static handlePermissionError(message: string): void {
    this.handle({
      type: BusinessErrorType.PERMISSION_DENIED,
      message: message
    }, {
      showMessage: true,
      showNotification: false,
      logToConsole: false
    })
  }

  /**
   * 处理数据不存在错误
   */
  static handleDataNotFoundError(message: string): void {
    this.handle({
      type: BusinessErrorType.DATA_NOT_FOUND,
      message: message
    }, {
      showMessage: true,
      showNotification: false,
      logToConsole: false
    })
  }

  /**
   * 处理业务规则错误
   */
  static handleBusinessRuleError(message: string): void {
    this.handle({
      type: BusinessErrorType.BUSINESS_RULE_VIOLATION,
      message: message
    }, {
      showMessage: true,
      showNotification: false,
      logToConsole: false
    })
  }
}

/**
 * 便捷函数：处理业务错误
 */
export function handleBusinessError(error: string | BusinessError, options?: {
  showMessage?: boolean
  showNotification?: boolean
  logToConsole?: boolean
  silent?: boolean
}): void {
  BusinessErrorHandler.handle(error, options)
}

/**
 * 便捷函数：处理权限错误
 */
export function handlePermissionError(message: string): void {
  BusinessErrorHandler.handlePermissionError(message)
}

/**
 * 便捷函数：处理数据不存在错误
 */
export function handleDataNotFoundError(message: string): void {
  BusinessErrorHandler.handleDataNotFoundError(message)
}

/**
 * 便捷函数：处理业务规则错误
 */
export function handleBusinessRuleError(message: string): void {
  BusinessErrorHandler.handleBusinessRuleError(message)
}

export default BusinessErrorHandler
